#ifndef __M_THREADPOOL_H__
#define __M_THREADPOOL_H__

#include<vector>
#include<thread>
#include<iostream>
#include<functional>
#include<mutex>
#include<future>
#include<condition_variable>

namespace mq{

const int& def_threadcount = 5;
//有点难
class ThreadPool{
    public:
    using ptr = std::shared_ptr<ThreadPool>;
    using fun_t = std::function<void(void)>;
        ThreadPool(int threadcount = def_threadcount):_running(true){
            for(int i = 0;i < threadcount;i++){
                _threads.emplace_back(&ThreadPool::entry,this);
            }
        }
        ~ThreadPool(){stop();}//别忘了
        template<typename F,typename ...Args>
        auto push(F&& func,Args&& ...args) -> std::future<decltype(func(args...))>{
            //1绑定无参函数
            using return_type = decltype(func(args...));
            auto noparameterfunc =  std::bind(std::forward<F>(func),std::forward<Args>(args)...);
            //2 绑future
            auto packageptr = std::make_shared<std::packaged_task<return_type()>>(noparameterfunc);
            // std::packaged_task<return_type()> ptask(noparameterfunc)
            std::future<return_type> fu = packageptr->get_future();
            //3线程
            {
                std::unique_lock<std::mutex> lock(_mutex);
                // std::cout<<std::this_thread::get_id()<<std::endl;
                _taskpool.push_back([packageptr](){
                    (*packageptr)();
                });
                _condvs.notify_one();
            }
            return fu;
        }
        void stop(){
            if(_running == false) return;
            _running = false;
            _condvs.notify_all();
            for(auto& th:_threads){
                th.join();
            }
        }

    private:
        void entry(){
            while(_running){
                std::vector<fun_t> tmp_tasks;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    _condvs.wait(lock,[this](){return !_running || !_taskpool.empty();});
                    tmp_tasks.swap(_taskpool);
                }
                for(auto& task : tmp_tasks){
                    task();
                }
            }
        }
    private:
        std::atomic<bool> _running;
        std::mutex _mutex;
        std::vector<fun_t> _taskpool;
        std::condition_variable _condvs;
        std::vector<std::thread> _threads;
};
}
#endif